import { Component, OnInit, Renderer2, ElementRef } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { HttpService } from 'src/app/service/http.service';
import { UrlService } from 'src/app/service/url.service';
import { ToolService } from 'src/app/service/tool.service';
import { ConfigService } from 'src/app/service/config.service';
import { NavController, Platform } from '@ionic/angular';
import { EventService } from 'src/app/service/event.service';
import { PopwinService } from 'src/app/service/popwin.service';
import { Storage } from '@ionic/storage';
import * as $ from 'jquery';
@Component({
  selector: 'app-login',
  templateUrl: './login.page.html',
  styleUrls: ['./login.page.scss'],
})
export class LoginPage implements OnInit {
  public onLoginForm: FormGroup;
  public isRemember: boolean = false;
  constructor(private formBuilder: FormBuilder, private http: HttpService, private navCtrl: NavController, private eventS: EventService, private popWin: PopwinService, private store: Storage, private plt: Platform,
    private renderer2: Renderer2, private element: ElementRef) { }

  ngOnInit() {
    this.onLoginForm = this.formBuilder.group({
      'username': [null, Validators.compose([
        Validators.required
      ])],
      'password': [null, Validators.compose([
        Validators.required
      ])]
    });

  }

  async forgotPass() {
    this.navCtrl.navigateForward("/findpsw");
  }

  onPlay() {
    this.testplayNet();
  }

  onLogin() {
    let remember = 0;
    if (this.isRemember) {
      remember = 1;
    }
    this.loginNet(this.onLoginForm.value.username, this.onLoginForm.value.password, remember);
  }

  registPage() {
    if (ConfigService.isAgent == 1) {
      this.navCtrl.navigateForward("/registagent");
    } else {
      this.navCtrl.navigateForward("/regist");
    }
  }

  backClick() {
    this.navCtrl.navigateBack("/");
  }

  testplayNet() {
    let that = this;
    this.http.get(UrlService.LOGIN_TESTPLAY, { "callback": "JSONP_CALLBACK" }).subscribe(res => {
      let data = res.json();
      ToolService.setEncrypt(data.encrypt);
      if (data.code == ConfigService.SUCCESS_CODE) {
        let tempData = ToolService.aesDecodeToJson(data.data);
        that.store.clear();
        that.store.set("token", tempData['access-token']);
        $("app-root").attr("token", tempData['access-token']);
        $("app-root").attr("uid", tempData['uid']);
        if (that.plt.is('ios')) {
          $("app-root").attr("sessid", tempData['sessid']);
        }
        that.store.set(ConfigService.FUID_KEY, tempData['fuid']);
        that.store.set("sessid", tempData['sessid']);
        that.store.set("uid", tempData['uid']);
        that.store.set(ConfigService.IS_LOGIN_STORE_KEY, "1");
        that.store.set(ConfigService.ROLE_KEY, tempData['role']);
        that.eventS.publish("updateMenu");
        that.eventS.publish("getSlideMenu", true);
        that.userInfo();
        that.navCtrl.navigateRoot("/");
        // that.lotRes = ToolService.aesDecodeToJson(data.data).data;
        // let xx=ToolService.aesDecodeToJson(data.data);
        // console.log(ToolService.aesDecode(data.data)['access-token']);
      } else {
        that.popWin.toast(data.message);
      }
    }, error => {
      that.popWin.toast(ToolService.newError(error));
    });
  }

  loginNet(username, psw, remember) {
    let that = this;
    let obj = "{\"username\":\"" + username + "\",\"password\":\"" + psw + "\",\"remember\":\"" + remember + "\"}";
    this.http.get(UrlService.LOGIN_LOGIN, { "callback": "JSONP_CALLBACK", "data": ToolService.aesEncode(obj) }).subscribe(res => {
      let data = res.json();
      ToolService.setEncrypt(data.encrypt);
      if (data.code == ConfigService.SUCCESS_CODE) {
        let tempData = ToolService.aesDecodeToJson(data.data);
        that.store.clear();
        that.store.set("token", tempData['access-token']);
        $("app-root").attr("token", tempData['access-token']);
        $("app-root").attr("sessid", tempData['sessid']);
        $("app-root").attr("uid", tempData['uid']);
        if (that.plt.is('ios')) {
          $("app-root").attr("sessid", tempData['sessid']);
        }
        that.store.set("sessid", tempData['sessid']);
        that.store.set("uid", tempData['uid']);
        that.store.set(ConfigService.FUID_KEY, tempData['fuid']);
        that.store.set(ConfigService.IS_LOGIN_STORE_KEY, "1");
        that.store.set(ConfigService.ROLE_KEY, tempData['role']);
        that.eventS.publish("updateMenu");
        that.eventS.publish("getSlideMenu", true);
        that.userInfo();
        that.navCtrl.navigateRoot("/");
        // that.lotRes = ToolService.aesDecodeToJson(data.data).data;
        // let xx=ToolService.aesDecodeToJson(data.data);
        // console.log(ToolService.aesDecode(data.data)['access-token']);
      } else {
        that.popWin.toast(data.message);
      }
    }, error => {
      // this.popWin.toast(ToolService.newError(error));
    });
  }

  /**
   * 存储用户的信息数据
   */
  userInfo() {
    let that = this;
    this.http.get(UrlService.USER_SHOWUSERINFO, { "callback": "JSONP_CALLBACK" }).subscribe(res => {
      let data = res.json();
      ToolService.setEncrypt(data.encrypt);
      if (data.code == ConfigService.SUCCESS_CODE) {
        //成功的逻辑
        that.store.set(ConfigService.USERINFO_KEY, ToolService.aesDecodeToJson(data.data));
      } else if (data.code == ConfigService.FAIL_CODE) {
        that.popWin.toast(data.message);
      } else if (data.code == ConfigService.LOGIN_CODE) {
        that.navCtrl.navigateForward("/login");
      }
    }, error => {
      console.log("error", error);
    });
  }


  ngAfterViewInit() {
    // 修改返回按钮中文本的样式
    const ionBackButton = this.element.nativeElement.querySelector('ion-checkbox');
    const styleSheet = `
      .checkbox-icon path  {
        stroke-width: 3px !important;
      }
    `;
    this.injectStyleToShadowRoot(this.renderer2, ionBackButton, styleSheet);
  }

  injectStyleToShadowRoot(renderer: Renderer2, element: HTMLElement, styleSheet: string): void {
    const style = renderer.createElement('style');
    style.innerHTML = styleSheet;
    element.shadowRoot.appendChild(style);
  }

}
